import * as vscode from 'vscode';
import * as path from 'path';
import { EnvironmentDetector } from './modules/environmentDetector';
import { ProxyServer } from './modules/proxyServer';
import { ConfigGenerator } from './modules/configGenerator';
import { ContainerManager } from './modules/containerManager';
import { PlatformHelper } from './modules/platformHelper';

// 简化的扩展入口
export function activate(context: vscode.ExtensionContext) {
    console.log('Nginx Config Visualizer extension is now active!');

    // 创建平台帮助器实例
    const platformHelper = PlatformHelper.getInstance();
    // 创建环境检测器实例
    const environmentDetector = new EnvironmentDetector();
    // 创建代理服务器实例
    const proxyServer = new ProxyServer();

    // 注册命令: 启动 Nginx (在编辑器内打开配置视图)
    context.subscriptions.push(
        vscode.commands.registerCommand('nginx-config-visualizer.startNginx', async () => {
            try {
                // 显示状态通知
                vscode.window.showInformationMessage('打开Nginx配置视图...');
                
                // 检测环境 (仅用于显示信息，不实际启动服务)
                const detectedEnvironment = await environmentDetector.detect();
                
                // 创建和显示编辑器内的WebView面板
                const panel = vscode.window.createWebviewPanel(
                    'nginxConfig',
                    'Nginx 配置',
                    vscode.ViewColumn.One,
                    {
                        enableScripts: true,
                        retainContextWhenHidden: true,
                        // 允许所有内容
                        localResourceRoots: [vscode.Uri.file(path.join(context.extensionPath))]
                    }
                );
                
                // 设置WebView内容
                panel.webview.html = getWebviewContent(panel.webview, detectedEnvironment.type);
                
                // 处理WebView消息
                panel.webview.onDidReceiveMessage(
                    message => {
                        switch (message.command) {
                            case 'saveConfig':
                                const config = message.config;
                                vscode.window.showInformationMessage(`配置已保存! 端口: ${config.port}`);
                                
                                // 如果用户配置了自动启动代理，启动代理服务器
                                if (config.startProxy && config.locations && config.locations.length > 0) {
                                    const proxyRules = config.locations
                                        .filter((loc: any) => loc.type === 'proxy')
                                        .map((loc: any) => ({
                                            path: loc.path,
                                            target: loc.proxyPass
                                        }));
                                    
                                    if (proxyRules.length > 0) {
                                        proxyServer.toggle(parseInt(config.port, 10), proxyRules);
                                    }
                                }
                                return;
                                
                            case 'startProxy':
                                const proxyConfig = message.config;
                                const port = parseInt(proxyConfig.port, 10);
                                const rules = proxyConfig.rules || [];
                                proxyServer.toggle(port, rules);
                                return;
                                
                            case 'stopProxy':
                                proxyServer.stop();
                                return;
                        }
                    },
                    undefined,
                    context.subscriptions
                );
            } catch (error) {
                vscode.window.showErrorMessage(`打开Nginx配置视图失败: ${error instanceof Error ? error.message : String(error)}`);
            }
        })
    );

    // 注册命令: 停止 Nginx (关闭编辑器内的配置视图)
    context.subscriptions.push(
        vscode.commands.registerCommand('nginx-config-visualizer.stopNginx', async () => {
            try {
                // 显示通知
                vscode.window.showInformationMessage('已关闭Nginx配置视图');
            } catch (error) {
                vscode.window.showErrorMessage(`关闭Nginx配置视图失败: ${error instanceof Error ? error.message : String(error)}`);
            }
        })
    );

    // 注册命令: 重启 Nginx (刷新编辑器内的配置视图)
    context.subscriptions.push(
        vscode.commands.registerCommand('nginx-config-visualizer.restartNginx', async () => {
            try {
                // 刷新配置视图
                vscode.commands.executeCommand('workbench.action.webview.reloadWebviewAction');
                vscode.window.showInformationMessage('已刷新Nginx配置视图');
            } catch (error) {
                vscode.window.showErrorMessage(`刷新Nginx配置视图失败: ${error instanceof Error ? error.message : String(error)}`);
            }
        })
    );

    // 注册命令: 打开配置界面
    context.subscriptions.push(
        vscode.commands.registerCommand('nginx-config-visualizer.openConfig', () => {
            // 执行启动命令来打开配置界面
            vscode.commands.executeCommand('nginx-config-visualizer.startNginx');
            vscode.window.showInformationMessage('已打开Nginx配置界面');
        })
    );

    // 注册命令: 检查平台信息
    context.subscriptions.push(
        vscode.commands.registerCommand('nginx-config-visualizer.platformInfo', async () => {
            const platformType = platformHelper.getPlatformType();
            const isWSL = platformHelper.isWSLEnvironment();
            vscode.window.showInformationMessage(`当前平台: ${platformType}, ${isWSL ? 'WSL环境' : '原生环境'}`);
        })
    );

    // 注册命令: 切换代理服务器状态
    context.subscriptions.push(
        vscode.commands.registerCommand('nginx-config-visualizer.toggleProxyServer', async () => {
            // 如果代理服务器已经运行，则停止它
            if (proxyServer.isRunning()) {
                proxyServer.stop();
            } else {
                // 否则，提示用户输入代理端口
                const portInput = await vscode.window.showInputBox({
                    prompt: '输入代理服务器端口',
                    placeHolder: '例如: 8081',
                    value: '8081'
                });
                
                if (!portInput) return;
                
                const port = parseInt(portInput, 10);
                if (isNaN(port) || port < 1 || port > 65535) {
                    vscode.window.showErrorMessage('无效的端口号。请输入1-65535之间的数字。');
                    return;
                }
                
                // 提示用户输入代理规则
                const pathInput = await vscode.window.showInputBox({
                    prompt: '输入代理路径',
                    placeHolder: '例如: /',
                    value: '/'
                });
                
                if (!pathInput) return;
                
                const targetInput = await vscode.window.showInputBox({
                    prompt: '输入代理目标',
                    placeHolder: '例如: http://localhost:3000',
                    value: 'http://localhost:3000'
                });
                
                if (!targetInput) return;
                
                // 启动代理服务器
                proxyServer.updateProxyRules([{ path: pathInput, target: targetInput }]);
                proxyServer.start(port);
            }
        })
    );

    // 注册必要的其他命令为空实现以避免错误
    ['validateConfig', 'manageInstances', 'showLogs', 'analyzeLog'].forEach(cmd => {
        context.subscriptions.push(
            vscode.commands.registerCommand(`nginx-config-visualizer.${cmd}`, () => {
                vscode.window.showInformationMessage(`命令"${cmd}"将在未来版本中实现。`);
            })
        );
    });
}

// 生成WebView内容的辅助函数
function getWebviewContent(webview: vscode.Webview, environmentType: string): string {
    const nonce = getNonce();
    
    return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline';">
    <title>Nginx 配置可视化</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            color: var(--vscode-editor-foreground);
            background-color: var(--vscode-editor-background);
        }
        h1 {
            color: var(--vscode-editor-foreground);
            border-bottom: 1px solid var(--vscode-panel-border);
            padding-bottom: 10px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, select, textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid var(--vscode-input-border);
            background-color: var(--vscode-input-background);
            color: var(--vscode-input-foreground);
            border-radius: 4px;
        }
        button {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        button:hover {
            background-color: var(--vscode-button-hoverBackground);
        }
        .tab {
            overflow: hidden;
            border: 1px solid var(--vscode-panel-border);
            background-color: var(--vscode-tab-inactiveBackground);
        }
        .tab button {
            background-color: inherit;
            float: left;
            border: none;
            outline: none;
            cursor: pointer;
            padding: 10px 15px;
            transition: 0.3s;
        }
        .tab button:hover {
            background-color: var(--vscode-tab-hoverBackground);
        }
        .tab button.active {
            background-color: var(--vscode-tab-activeBackground);
        }
        .tabcontent {
            display: none;
            padding: 15px;
            border: 1px solid var(--vscode-panel-border);
            border-top: none;
        }
        .env-info {
            padding: 10px;
            margin-bottom: 20px;
            background-color: var(--vscode-editorInfo-background);
            border-left: 4px solid var(--vscode-infoButton-background);
            color: var(--vscode-editorInfo-foreground);
        }
        #GeneralTab {
            display: block;
        }
    </style>
</head>
<body>
    <div class="env-info">
        <strong>环境信息:</strong> ${environmentType === 'none' ? '使用内置代理' : `使用 ${environmentType}`}
    </div>
    
    <h1>Nginx 配置可视化</h1>
    
    <div class="tab">
        <button class="tablinks active" id="btn-general">基本设置</button>
        <button class="tablinks" id="btn-locations">路由规则</button>
        <button class="tablinks" id="btn-advanced">高级设置</button>
        <button class="tablinks" id="btn-config">配置预览</button>
    </div>
    
    <div id="GeneralTab" class="tabcontent">
        <h2>基本设置</h2>
        <div class="form-group">
            <label for="port">监听端口</label>
            <input type="number" id="port" value="8080" min="1" max="65535">
        </div>
        <div class="form-group">
            <label for="server_name">服务器名称</label>
            <input type="text" id="server_name" value="localhost">
        </div>
        <div class="form-group">
            <label for="gzip">启用Gzip压缩</label>
            <select id="gzip">
                <option value="true">是</option>
                <option value="false">否</option>
            </select>
        </div>
    </div>
    
    <div id="LocationsTab" class="tabcontent">
        <h2>路由规则</h2>
        <div id="locations-container">
            <div class="location-item">
                <div class="form-group">
                    <label>路径</label>
                    <input type="text" class="location-path" value="/">
                </div>
                <div class="form-group">
                    <label>类型</label>
                    <select class="location-type">
                        <option value="static">静态文件</option>
                        <option value="proxy">反向代理</option>
                        <option value="redirect">重定向</option>
                    </select>
                </div>
                <div class="form-group location-value static-input">
                    <label>文件根路径</label>
                    <input type="text" value="/usr/share/nginx/html">
                </div>
                <div class="form-group location-value proxy-input" style="display:none;">
                    <label>代理目标地址</label>
                    <input type="text" value="http://localhost:3000">
                </div>
                <div class="form-group location-value redirect-input" style="display:none;">
                    <label>重定向地址</label>
                    <input type="text" value="https://example.com">
                </div>
            </div>
        </div>
        <button id="btn-add-location">添加路由规则</button>
    </div>
    
    <div id="AdvancedTab" class="tabcontent">
        <h2>高级设置</h2>
        <div class="form-group">
            <label for="client_max_body_size">最大请求体大小</label>
            <input type="text" id="client_max_body_size" value="10m">
        </div>
        <div class="form-group">
            <label for="ssl">启用HTTPS</label>
            <select id="ssl">
                <option value="false">否</option>
                <option value="true">是</option>
            </select>
        </div>
        <div id="ssl-options" style="display:none">
            <div class="form-group">
                <label for="ssl_certificate">SSL证书路径</label>
                <input type="text" id="ssl_certificate" value="/etc/nginx/ssl/server.crt">
            </div>
            <div class="form-group">
                <label for="ssl_certificate_key">SSL密钥路径</label>
                <input type="text" id="ssl_certificate_key" value="/etc/nginx/ssl/server.key">
            </div>
        </div>
    </div>
    
    <div id="ConfigTab" class="tabcontent">
        <h2>配置预览</h2>
        <div class="form-group">
            <textarea id="config_preview" rows="20" readonly style="font-family: monospace;"></textarea>
        </div>
    </div>
    
    <div style="margin-top: 20px">
        <button id="btn-save">保存配置</button>
        <button id="btn-reset">重置</button>
        <button id="btn-preview">生成预览</button>
        <div style="margin-top: 10px">
            <input type="checkbox" id="startProxy" name="startProxy"> 
            <label for="startProxy">保存时自动启动代理服务器</label>
        </div>
        <div style="margin-top: 10px">
            <button id="btn-start-proxy">启动代理服务器</button>
            <button id="btn-stop-proxy">停止代理服务器</button>
        </div>
    </div>
    
    <script nonce="${nonce}">
        (function() {
            const vscode = acquireVsCodeApi();
            
            // Tab 切换功能
            function openTab(tabName) {
                // 隐藏所有标签内容
                const tabcontents = document.getElementsByClassName("tabcontent");
                for (let i = 0; i < tabcontents.length; i++) {
                    tabcontents[i].style.display = "none";
                }
                
                // 移除所有标签按钮的 active 类
                const tablinks = document.getElementsByClassName("tablinks");
                for (let i = 0; i < tablinks.length; i++) {
                    tablinks[i].className = tablinks[i].className.replace(" active", "");
                }
                
                // 显示当前标签并添加 active 类到按钮
                document.getElementById(tabName).style.display = "block";
                document.getElementById('btn-' + tabName.replace('Tab', '').toLowerCase()).className += " active";
                
                // 如果是配置预览标签，自动生成预览
                if (tabName === 'ConfigTab') {
                    generatePreview();
                }
            }
            
            // 添加标签点击事件
            document.getElementById('btn-general').addEventListener('click', function() {
                openTab('GeneralTab');
            });
            
            document.getElementById('btn-locations').addEventListener('click', function() {
                openTab('LocationsTab');
            });
            
            document.getElementById('btn-advanced').addEventListener('click', function() {
                openTab('AdvancedTab');
            });
            
            document.getElementById('btn-config').addEventListener('click', function() {
                openTab('ConfigTab');
            });
            
            // 添加SSL选项显示逻辑
            document.getElementById('ssl').addEventListener('change', function() {
                const sslOptions = document.getElementById('ssl-options');
                if (this.value === 'true') {
                    sslOptions.style.display = 'block';
                } else {
                    sslOptions.style.display = 'none';
                }
            });
            
            // 添加路由规则
            document.getElementById('btn-add-location').addEventListener('click', function() {
                const container = document.getElementById('locations-container');
                const newLocation = document.createElement('div');
                newLocation.className = 'location-item';
                newLocation.innerHTML = 
                    '<div class="form-group">' +
                    '<label>路径</label>' +
                    '<input type="text" class="location-path" value="/api">' +
                    '</div>' +
                    '<div class="form-group">' +
                    '<label>类型</label>' +
                    '<select class="location-type">' +
                    '<option value="static">静态文件</option>' +
                    '<option value="proxy" selected>反向代理</option>' +
                    '<option value="redirect">重定向</option>' +
                    '</select>' +
                    '</div>' +
                    '<div class="form-group location-value static-input" style="display:none;">' +
                    '<label>文件根路径</label>' +
                    '<input type="text" value="/usr/share/nginx/html">' +
                    '</div>' +
                    '<div class="form-group location-value proxy-input">' +
                    '<label>代理目标地址</label>' +
                    '<input type="text" value="http://localhost:3000">' +
                    '</div>' +
                    '<div class="form-group location-value redirect-input" style="display:none;">' +
                    '<label>重定向地址</label>' +
                    '<input type="text" value="https://example.com">' +
                    '</div>' +
                    '<button class="btn-remove-location">删除</button>';
                container.appendChild(newLocation);
                
                // 为新添加的删除按钮添加事件处理
                newLocation.querySelector('.btn-remove-location').addEventListener('click', function() {
                    container.removeChild(newLocation);
                });
                
                // 为新添加的类型选择添加事件处理
                const typeSelect = newLocation.querySelector('.location-type');
                typeSelect.addEventListener('change', function() {
                    changeLocationType(typeSelect);
                });
            });

            // 添加类型切换函数
            function changeLocationType(selectElement) {
                const locationItem = selectElement.closest('.location-item');
                const staticInput = locationItem.querySelector('.static-input');
                const proxyInput = locationItem.querySelector('.proxy-input');
                const redirectInput = locationItem.querySelector('.redirect-input');
                
                // 隐藏所有输入
                staticInput.style.display = 'none';
                proxyInput.style.display = 'none';
                redirectInput.style.display = 'none';
                
                // 显示对应类型的输入
                switch (selectElement.value) {
                    case 'static':
                        staticInput.style.display = 'block';
                        break;
                    case 'proxy':
                        proxyInput.style.display = 'block';
                        break;
                    case 'redirect':
                        redirectInput.style.display = 'block';
                        break;
                }
            }

            // 初始化所有类型选择的事件
            document.querySelectorAll('.location-type').forEach(function(select) {
                select.addEventListener('change', function() {
                    changeLocationType(this);
                });
            });
            
            // 生成预览
            function generatePreview() {
                const port = document.getElementById('port').value;
                const serverName = document.getElementById('server_name').value;
                const gzip = document.getElementById('gzip').value === 'true';
                const clientMaxBodySize = document.getElementById('client_max_body_size').value;
                const ssl = document.getElementById('ssl').value === 'true';
                
                let config = 'server {\\n';
                config += '    listen ' + port + (ssl ? ' ssl' : '') + ';\\n';
                config += '    server_name ' + serverName + ';\\n';
                
                if (ssl) {
                    const sslCert = document.getElementById('ssl_certificate').value;
                    const sslKey = document.getElementById('ssl_certificate_key').value;
                    config += '    ssl_certificate ' + sslCert + ';\\n';
                    config += '    ssl_certificate_key ' + sslKey + ';\\n';
                    config += '    ssl_protocols TLSv1.2 TLSv1.3;\\n';
                }
                
                if (gzip) {
                    config += '    gzip on;\\n';
                    config += '    gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;\\n';
                }
                
                config += '    client_max_body_size ' + clientMaxBodySize + ';\\n\\n';
                
                // 处理路由规则
                const locationItems = document.querySelectorAll('.location-item');
                locationItems.forEach(function(item) {
                    const path = item.querySelector('.location-path').value;
                    const type = item.querySelector('.location-type').value;
                    
                    config += '    location ' + path + ' {\\n';
                    
                    if (type === 'static') {
                        const rootPath = item.querySelector('.static-input input').value;
                        config += '        root ' + rootPath + ';\\n';
                        config += '        index index.html index.htm;\\n';
                    } else if (type === 'proxy') {
                        const proxyPass = item.querySelector('.proxy-input input').value;
                        config += '        proxy_pass ' + proxyPass + ';\\n';
                        config += '        proxy_set_header Host \\$host;\\n';
                        config += '        proxy_set_header X-Real-IP \\$remote_addr;\\n';
                        config += '        proxy_set_header X-Forwarded-For \\$proxy_add_x_forwarded_for;\\n';
                    } else if (type === 'redirect') {
                        const redirectUrl = item.querySelector('.redirect-input input').value;
                        config += '        return 301 ' + redirectUrl + ';\\n';
                    }
                    
                    config += '    }\\n\\n';
                });
                
                config += '}';
                
                document.getElementById('config_preview').value = config;
            }
            
            // 保存配置
            document.getElementById('btn-save').addEventListener('click', function() {
                // 收集配置信息
                const config = {
                    port: document.getElementById('port').value,
                    serverName: document.getElementById('server_name').value,
                    gzip: document.getElementById('gzip').value === 'true',
                    clientMaxBodySize: document.getElementById('client_max_body_size').value,
                    ssl: document.getElementById('ssl').value === 'true',
                    startProxy: document.getElementById('startProxy').checked, // 新增的代理启动选项
                    locations: Array.from(document.querySelectorAll('.location-item')).map(item => ({
                        path: item.querySelector('.location-path').value,
                        type: item.querySelector('.location-type').value,
                        staticPath: item.querySelector('.static-input input').value,
                        proxyPass: item.querySelector('.proxy-input input').value,
                        redirectUrl: item.querySelector('.redirect-input input').value
                    }))
                };
                
                // 通知VSCode扩展
                vscode.postMessage({
                    command: 'saveConfig',
                    config: config
                });
            });
            
            // 重置表单
            document.getElementById('btn-reset').addEventListener('click', function() {
                document.getElementById('port').value = '8080';
                document.getElementById('server_name').value = 'localhost';
                document.getElementById('gzip').value = 'true';
                document.getElementById('client_max_body_size').value = '10m';
                document.getElementById('ssl').value = 'false';
                document.getElementById('ssl-options').style.display = 'none';
                
                // 重置路由规则（保留第一个，删除其余的）
                const container = document.getElementById('locations-container');
                const items = container.querySelectorAll('.location-item');
                
                if (items.length > 0) {
                    const firstItem = items[0];
                    firstItem.querySelector('.location-path').value = '/';
                    firstItem.querySelector('.location-type').value = 'static';
                    firstItem.querySelector('.location-value input').value = '/usr/share/nginx/html';
                    
                    // 删除其他项
                    for (let i = items.length - 1; i > 0; i--) {
                        container.removeChild(items[i]);
                    }
                }
                
                // 更新预览
                if (document.getElementById('ConfigTab').style.display === 'block') {
                    generatePreview();
                }
            });
            
            // 生成预览按钮
            document.getElementById('btn-preview').addEventListener('click', generatePreview);
            
            // 添加代理服务器控制
            document.getElementById('btn-start-proxy').addEventListener('click', function() {
                // 收集配置信息
                const port = document.getElementById('port').value;
                
                // 收集代理规则
                const rules = Array.from(document.querySelectorAll('.location-item'))
                    .filter(item => item.querySelector('.location-type').value === 'proxy')
                    .map(item => ({
                        path: item.querySelector('.location-path').value,
                        target: item.querySelector('.proxy-input input').value
                    }));
                
                if (rules.length === 0) {
                    alert('请至少添加一条反向代理规则');
                    return;
                }
                
                // 通知VSCode扩展
                vscode.postMessage({
                    command: 'startProxy',
                    config: {
                        port: port,
                        rules: rules
                    }
                });
            });

            document.getElementById('btn-stop-proxy').addEventListener('click', function() {
                // 通知VSCode扩展
                vscode.postMessage({
                    command: 'stopProxy'
                });
            });
            
            // 初始化时生成预览
            generatePreview();
        })();
    </script>
</body>
</html>`;
}

// 生成随机的nonce值，用于Content-Security-Policy
function getNonce() {
    let text = '';
    const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (let i = 0; i < 32; i++) {
        text += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return text;
}

export function deactivate() {
    console.log('Nginx 配置可视化插件已停用。');
} 